// pages/login/login.js
const sharePost = require('../../request/sharePost.js')
//获取应用实例
const app = getApp()

Page({
  data: {
    isSalesman:false,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    openid: '',
    code: '',
    url: '',
    userType: '',
    isUser: false,
    isShouQuan: false,
    hasLogin: false,
    disabled: true,
    opacity: 0.4
  },
  inputChange: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () { },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: true
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  closePage: function() {
    wx.showModal({
      title: '确认取消授权吗',
      content: '取消授权将不能进行分享',
    })
  },
  /**
   * 隐藏登录框
   */
  hideLoginModal: function () {
    let that = this
    wx.getSetting({
      success(res) {
        if (JSON.stringify(res.authSetting) === "{}" || res.authSetting['scope.userInfo'] == false) {
          console.log('拒绝授权')
        } else {
          console.log('已授权11', JSON.stringify(res.authSetting))
          that.setData({
            isShouQuan: false
          })
          if (that.data.hasLogin) {
            console.log('已授权已注册')
            that.hasShouQuanHasRes()
          } else {
            console.log('已授权未注册')
            that.hasShouQuanNunRes()
          }
        }
      }
    })
  },
  /**
   * 填写邀请码确认按钮点击事件
   */
  onConfirm: function () {
    if (this.data.code === '') {
      wx.showToast({
        title: '邀请码不能为空',
        icon: 'none',
        duration: 2000
      })
    } else {
      sharePost.validateInviteCode({
        code: this.data.code
      }).then(res => {
        if (res.code === -1) {
          wx.showToast({
            title: '验证码错误',
            icon: 'none',
            duration: 2000
          })
        } else {
          console.log('填写邀请码的请求的res', res.data)
          var invite = res.data
          console.log("res.data.user_name", res.data.openid)
          wx.navigateTo({
            url: '../complete/complete?user_type=0&invite=' + invite + '&invite_name=' + res.data.user_name + '&invite_phone=' + res.data.user_phone + '&sid=' + res.data.uid + '&openid=' + res.data.openid,
          })
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
          })
          this.setData({
            showModal: false,
            disabled: false,
            opacity: 0.9
          });
          app.globalData.user_type = 0
          app.globalData.info.user_type = 0
        }
      })
    }
  },
  /**
   * 获取授权后的个人信息
   */
  onLoad: function () {
    this.app = getApp();
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    //检查是否存在新版本
    wx.getUpdateManager().onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log("是否有新版本：", res.hasUpdate);
      if (res.hasUpdate) {//如果有新版本
        wx.hideLoading()
        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateReady(function () {//当新版本下载完成，会进行回调
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，单击确定重启应用',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.getUpdateManager().applyUpdate();
              }
            }
          })
        })
        // 小程序有新版本，会主动触发下载操作（无需开发者触发）
        wx.getUpdateManager().onUpdateFailed(function () {//当新版本下载失败，会进行回调
          wx.showModal({
            title: '提示',
            content: '检查到有新版本，但下载失败，请检查网络设置',
            showCancel: false,
          })
        })
      } else {
        console.log("执行判断是否授权")
        wx.getSetting({
          success(res) {
            let userSq = res.authSetting['scope.userInfo']
            console.log("ddd授权", res, res.authSetting['scope.userInfo'])
            wx.login({
              success: function (res) {
                if (res.code) {
                  //发起网络请求
                  let params = {
                    "code": res.code
                  }
                  console.log('获取params', params)
                  sharePost.getOpenId(params).then(res => {
                    if (res.openid) {
                      that.setData({
                        openid: res.openid
                      })
                      app.globalData.info.openid = res.openid
                      console.log('获取openId', res, that.data.hasUserInfo)
                      sharePost.userInfoGet({
                        "openid": res.openid
                      }).then(res => {
                        console.log('获取_id', res)
                        if (res.code === -1) {
                          that.setData({
                            hasUserInfo: false
                          })
                        } else {
                          that.setData({
                            hasUserInfo: true
                          })
                          app.globalData.info._id = res.data._id
                          app.globalData.info = res.data
                        }
                        if (!userSq) {
                          console.log("未授权")
                          that.setData({
                            disabled: false,
                            opacity: 0.9
                          })
                          if (that.data.hasUserInfo) {
                            console.log("有信息")
                            that.setData({
                              hasLogin: true
                            })
                          }
                          wx.hideLoading()
                        } else {
                          console.log("判断授权与注册", that.data.hasUserInfo, userSq)
                          if (that.data.hasUserInfo && userSq) {
                            console.log("已授权已注册", res.openid, that.data.hasUserInfo, userSq)
                            that.hasShouQuanHasRes()
                          } else {
                            console.log("已授权未注册")
                            wx.hideLoading()
                            that.hasShouQuanNunRes()
                          }
                        }
                      })
                    }
                    if (res.errcode) {
                      wx.showToast({
                        title: '登录失败',
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  })
                } else {
                  console.log('获取用户登录失败！' + res.errMsg)
                }
              }
            })
          }
        })
      }
    })
  },
  /**
   * 已授权未注册
   */
  hasShouQuanNunRes() {
    let that = this
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    app.globalData.user_type = parseInt(options.user_type)
    wx.getUserInfo({
      success: res => {
        app.globalData.userInfo = res.userInfo
        this.setData({
          userInfo: res.userInfo
        })
      },
      fail: function () {
        console.log('授权失败')
      }
    })
    if (JSON.stringify(options) !== "{}") {
      //业务员登录
      app.globalData.info.user_type = parseInt(options.user_type)
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            let params = {
              "code": res.code
            }
            wx.showLoading({
              title: '登录中',
            })
            sharePost.getOpenId(params).then(res => {
              console.log('获取openId', res)
              if (res.openid) {
                that.setData({
                  openid: res.openid,
                  hasUserInfo: true,
                  disabled: false,
                  opacity: 0.9
                })
                wx.hideLoading()
                wx.navigateTo({
                  url: '../complete/complete?user_type=1&openid=' + res.openid
                })
              }
              if (res.errcode) {
                wx.showToast({
                  title: '登录失败',
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          } else {
            console.log('获取用户登录失败！' + res.errMsg)
          }
        }
      })
    } else {
      //填写邀请码-普通会员登录
      that.setData({
        isShouQuan: false,
        showModal: true
      })
    }
  },
  /**
   * 已授权已注册
   */
  hasShouQuanHasRes() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    console.log('JSON.stringify(options)', JSON.stringify(options) !== '{}')
    app.globalData.user_type = (JSON.stringify(options) !== '{}') ? parseInt(options.user_type) : 0
    wx.getUserInfo({
      success: res => {
        console.log('授权成功', res)
        app.globalData.userInfo = res.userInfo
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          disabled: false,
          opacity: 0.9,
          hasLogin: true,
          isUser: true
        })
        wx.hideLoading()
        wx.navigateTo({
          url: '../main/main'
        })
      },
      fail: function () {
        console.log('授权失败')
      }
    })
  },
  goToUrl(e) {
    console.log("sksdjfkd")
    let that = this
    that.setData({
      url: e.currentTarget.dataset.url
    })
    if (that.data.isUser) {
      wx.navigateTo({
        url: '../main/main',
      })
    } else {
      console.log("点击登录弹窗弹窗")
      that.setData({
        isShouQuan: true
      });
    }
  },
  //页面展示时，触发动画
  onShow: function () {
  }
})
